package com.hzy.infrastructure;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 工具类
 */
public class Tools {

    private static final Logger LOGGER = LoggerFactory.getLogger(Tools.class);

    /**
     * 判断是否 Ajax
     *
     * @param request
     * @return
     */
    public static Boolean isAjaxRequest(HttpServletRequest request) {
        String key = "X-Requested-With";
        String value = "XMLHttpRequest";
        String xRequestedWidth = request.getHeader(key);

        if (ObjectUtils.isEmpty(xRequestedWidth)) {
            return false;
        }

        return value.equals(xRequestedWidth);
    }

    /**
     * null 安全函数 |
     * 空指针 安全函数
     *
     * @param target
     * @param defaultValue
     * @param <T>
     * @return
     */
    public static <T> T nullSafe(final T target, final T defaultValue) {
        return (target != null ? target : defaultValue);
    }

    /**
     * 数组连接字符串
     *
     * @param list
     * @param delimiter
     * @return
     */
    public static String joinString(ArrayList<String> list, String delimiter) {
        String res = "";

        for (int i = 0; i < list.size(); i++) {
            String item = list.get(i);
            if (list.size() - 1 == i) {
                res += item;
            } else {
                res += item + delimiter;
            }
        }

        return res;
    }

    /**
     * 获取一个 uuid
     *
     * @return
     */
    public static String getUUID() {
        return UUID.randomUUID().toString();
    }

    /**
     * 获取 ip
     *
     * @param request
     * @return
     */
    public static String getRemoteIp(javax.servlet.http.HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
    }

    /**
     * 从request中获取json
     *
     * @param request
     * @return
     */
    public static String getJsonStringByBody(ServletRequest request) {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = null;
        try (InputStream inputStream = request.getInputStream()) {
            reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            LOGGER.warn("getBodyString出现问题！");
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    // ExceptionUtils.getFullStackTrace(e)
                    LOGGER.error(e.getMessage());
                }
            }
        }
        return sb.toString();
    }

    /**
     * 获取 地址栏数据 为 map 对象
     *
     * @return
     */
    public static Map<String, Object> getQueryStringMap(final String queryString) {
        Map<String, Object> res = new HashMap<>();
        if (ObjectUtils.isEmpty(queryString)) {
            return res;
        }

        if (!queryString.contains("&") && queryString.contains("=")) {
            String[] keyValue = StringUtils.split(queryString, "=");

            if (keyValue == null) {
                return res;
            }

            if (keyValue.length == 0) {
                return res;
            }

            res.put(keyValue[0], keyValue[1]);

            return res;
        }

        String[] keyValues = StringUtils.split(queryString, "&");

        if (keyValues == null) {
            return res;
        }

        if (keyValues.length == 0) {
            return res;
        }

        for (String item : keyValues) {
            String[] keyValue = StringUtils.split(item, "=");

            if (keyValue == null) {
                continue;
            }

            if (keyValue.length == 0) {
                continue;
            }

            res.put(keyValue[0], keyValue[1]);
        }
        return res;
    }

    /**
     * 返回 Json 数据
     *
     * @param response
     * @param data
     * @throws Exception
     */
    public static void jsonResult(HttpServletResponse response, Object data) throws Exception {
        response.setContentType("application/json; charset=utf-8");
        PrintWriter printWriter = response.getWriter();
        printWriter.print(JSON.toJSONString(data));
        printWriter.flush();
        printWriter.close();
    }

    /**
     * 返回 文本 数据
     *
     * @param response
     * @param msg
     * @throws Exception
     */
    public static void contentResult(HttpServletResponse response, StringBuilder msg) throws Exception {
        Tools.contentResult(response, msg, "text/html; charset=utf-8");
    }

    /**
     * 返回 文本 数据
     *
     * @param response
     * @param msg
     * @throws Exception
     */
    public static void contentResult(HttpServletResponse response, StringBuilder msg, String contentType) throws Exception {
        response.setContentType(contentType);
        PrintWriter printWriter = response.getWriter();
        printWriter.print(msg);
        printWriter.flush();
        printWriter.close();
    }

    /**
     * 转化为大驼峰
     *
     * @param name
     * @return
     */
    public static String getUpperCamelCase(String name) {
        if (name == null || "".equals(name)) {
            return "";
        }
        String[] strings = name.split("[^a-zA-Z0-9]+");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < strings.length; i++) {
            sb.append(getTitleCase(strings[i]));
        }
        return sb.toString();
    }

    /**
     * 转化为小驼峰
     *
     * @param name
     * @return
     */
    public static String getLowerCamelCase(String name) {
        name = getUpperCamelCase(name);
        return name.substring(0, 1).toLowerCase() + name.substring(1);
    }

    private static String getTitleCase(String name) {
        if (name == null || "".equals(name)) {
            return "";
        }
        return name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase();
    }


}
